﻿#region ... Copyright Notice ...
/*
   Copyright 2008 Tyler Jensen

	Author: Tyler Jensen    http://www.tsjensen.com/blog

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
#endregion

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;

namespace Atrax.Web.Test
{
	public partial class _Default : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}

		protected void btnRunQuery_Click(object sender, EventArgs e)
		{
			string clientQueryId = txtClientQueryId.Text;
			string queryType = txtQueryType.Text;
			string queryRequest = txtQuery.Text;
			int priority = 100;
			if (!int.TryParse(txtPriority.Text, out priority)) priority = 100;
			string query = QueryFactory.Create(clientQueryId, queryType, priority, queryRequest);

			string url = ConfigurationManager.AppSettings["atraxDispatcherUrl"] + "?" + query;

			string response = string.Empty;
			try
			{
				HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
				req.Timeout = 180000; //miliseconds
				req.Method = "GET";
				using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
				{
					using (Stream s = resp.GetResponseStream())
					{
						byte[] data = this.ReadStreamData(s);
						if (resp.StatusCode == HttpStatusCode.OK)
						{
							response = Encoding.UTF8.GetString(data);
						}
						else
							throw new Exception("Response error: " + resp.StatusCode.ToString() + " " + resp.StatusDescription);
					}
				}
			}
			catch (Exception ex)
			{
				response = ex.ToString();
			}
			divResponse.InnerText = response;
		}

		byte[] ReadStreamData(Stream s)
		{
			byte[] data = null;
			int tries = 0;
			while (data == null && tries < 3) //try 3 times before giving up on reading data
			{
				if (tries > 0) System.Threading.Thread.Sleep(50); //wait on the thread 50ms 
				while (true)
				{
					byte[] readdata = new byte[2048];
					int recv = 0;
					try
					{
						recv = s.Read(readdata, 0, readdata.Length); //.NET 2.0 timeout throws error otherwise waits to read infinitely
					}
					catch
					{
						recv = 0; //TODO - deal with timeout, use something to mark it and set the ResponseCode and ResponseMessage
					}
					if (recv > 0)
					{
						if (data != null) //append
						{
							byte[] comb = new byte[data.Length + recv];
							Array.Copy(data, 0, comb, 0, data.Length); //copy data to combination
							Array.Copy(readdata, 0, comb, data.Length, recv); //copy readdata to combination
							data = new byte[comb.Length]; //remake data
							Array.Copy(comb, data, comb.Length); //copy combination to data
						}
						else //copy to data for first time
						{
							data = new byte[recv];
							Array.Copy(readdata, 0, data, 0, recv);
						}
					}
					else
					{
						break;
					}
				}
				tries++;
			}
			return data;
		}

	}
}
